#encoding=utf-8
'''

    专门用来做断言的方法库

'''
import copy

import pymysql

from config import setting


class AssertUtil:

    # 链接数据库
    def connect_db(self):
        self.conn = pymysql.connect(
            host=setting.db_host,
            password=setting.db_password,
            database=setting.db_database,
            user=setting.db_username,
            port=setting.db_port
        )
        return self.conn

    # 执行数据库语句
    def execute_db(self, sql):
        # 创建数据库连接
        conn = self.connect_db()
        #创建游标
        cs = conn.cursor()
        try:
            # 执行sql语句
            cs.execute(sql)
            # 获取执行的sql语句结果
            res = cs.fetchall()
        except Exception as e:
            raise e
        #关闭资源
        cs.close()
        conn.close()
        #返回值
        return res


    def assert_util(self,res, assert_type, value):
        # 1、深拷贝结果
        new_res = copy.deepcopy(res)
        # 2、把json方法转化为json属性
        try:
            new_res.json = new_res.json()
        except Exception as e:
            new_res.json = {"msg":"response is not a json"}
            raise e
        # 3、循环判断断言
        for msg, yuqi_shiji_value in value.items():
            # 根据定义的形式获取对应的值[预期，实际]
            yuqi,shiji = yuqi_shiji_value[0],yuqi_shiji_value[1]
            # 根据对应的属性获取对应的值
            try:
                # 尝试从响应对象中获取实际值
                shiji_value = getattr(new_res, shiji)
                # print("++++", assert_type, msg, yuqi, shiji_value)
            except Exception as e:
                # 如果属性不存在，记录警告并保留原始键名作为标记
                print(f"Warning: '{shiji}' attribute not found in response object.")
                shiji_value = shiji  # 保留原始键名以便后续识别

            # 判断断言
            match assert_type:
                case "equals":
                    assert yuqi == shiji_value, f"{msg}断言失败，预期结果是：{yuqi}，实际结果是：{shiji_value}"
                case "contains":
                    assert yuqi in shiji_value, f"{msg}断言失败，预期结果是：{yuqi}，实际结果是：{shiji_value}"
                case "db_contains":
                    yuqi_value = self.execute_db(yuqi)
                    yuqi_value_str = str(*yuqi_value[0])
                    assert yuqi_value_str in str(shiji_value), f"{msg}断言失败，预期结果是：{yuqi_value}，实际结果是：{shiji_value}"


if __name__ == '__main__':
    value = AssertUtil().execute_db("select cname from course")
    print(value)

